﻿using Microsoft.AspNetCore.Http;
using System;
using System.Drawing;
using System.IO;
using System.Web;

namespace Colorful.Captcha
{
    /// <summary>
    /// 验证码帮助类
    /// </summary>
    public static class CaptchaHelper
    {
        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <param name="sessionName">Session名称</param>
        /// <param name="length">验证码位数</param>
        /// <returns></returns>
        public static byte[] GetCaptcha(string sessionName = "code", int length = 4)
        {
            var code = CommonHelper.GetRandomAllStr(length);
            System.Web.HttpContext.Current.Session.SetString(sessionName, code);
            Bitmap Img = null;
            Graphics g = null;
            MemoryStream ms = null;
            Random random = new Random();
            //验证码颜色集合  
            Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };

            //验证码字体集合
            string[] fonts = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };


            //定义图像的大小，生成图像的实例  
            Img = new Bitmap((int)code.Length * 18, 48);

            g = Graphics.FromImage(Img);//从Img对象生成新的Graphics对象    

            g.Clear(Color.White);//背景设为白色  

            //在随机位置画背景点  
            for (int i = 0; i < 100; i++)
            {
                int x = random.Next(Img.Width);
                int y = random.Next(Img.Height);
                g.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1);
            }
            //验证码绘制在g中  
            for (int i = 0; i < code.Length; i++)
            {
                int cindex = random.Next(7);//随机颜色索引值  
                int findex = random.Next(5);//随机字体索引值  
                Font f = new Font(fonts[findex], 15, FontStyle.Bold);//字体  
                Brush b = new SolidBrush(c[cindex]);//颜色  
                int ii = 14;
                if ((i + 1) % 2 == 0)//控制验证码不在同一高度  
                {
                    ii = 7;
                }
                g.DrawString(code.Substring(i, 1), f, b, 3 + (i * 15), ii);//绘制一个验证字符  
            }
            ms = new MemoryStream();//生成内存流对象  
            Img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);//将此图像以Png图像文件的格式保存到流中  

            //回收资源  
            g.Dispose();
            Img.Dispose();
            return ms.ToArray();
        }
        /// <summary>
        /// 检测验证码是否有效
        /// </summary>
        /// <param name="code">验证码</param>
        /// <param name="name">Session名称</param>
        /// <returns></returns>
        public static bool IsValid(string code, string name = null)
        {
            if (string.IsNullOrEmpty(code))
                return false;
            try
            {
                if (string.IsNullOrEmpty(name))
                    name = "code";
                string sessionCode = System.Web.HttpContext.Current.Session.GetString(name);
                if (string.IsNullOrEmpty(sessionCode))
                    return false;
                return sessionCode.Equals(code, StringComparison.CurrentCultureIgnoreCase);
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
